package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.ExifInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.Expert;
import com.isunland.managesystem.entity.SeniorExpert;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.GPSToGCJUtil;
import com.isunland.managesystem.utils.LocationUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * 对象功能:  帖子发布界面
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/17 17:18
 * E4:24:1F:02:8B:37:F8:5A:FC:6B:44:FF:A9:62:B3:CD:C3:3C:B4:52
 */
public class AgriculturalTopicPublishFragment extends BaseFragment implements View.OnClickListener {

  //作物圈content
  public static final String EXTRA_FORUM_TYPE =
      AgriculturalTopicPublishFragment.class + "EXTRA_FORUM_TYPE";
  //我的话题的发布还是其他做物圈的发布
  public static final String EXTRA_TYPE = AgriculturalTopicPublishFragment.class + "EXTRA_TYPE";
  //专家content,区分是咨询还是发布,专家咨询隐藏可见范围
  protected static final String EXTRA_FROM = AgriculturalTopicPublishFragment.class + "EXTRA_FROM";
  protected static final String SELF = "self";//来自我的话题的发布,需要选择作物圈类别
  private static final int CHOOSE_FILE = 0;
  private static final int REQUEST_TOPIC_KIND = 1;
  private static final int REQUEST_FRIEND = 2;
  private static final int REQUEST_CIRCLE = 3;
  private static final int REQUEST_EXPERT = 4;
  private static final int REQUEST_PICTUREA = 5;
  private static final int REQUEST_PICTUREB = 6;
  private static final int REQUEST_PICTUREC = 7;
  private static final int REQUEST_PICTURED = 8;
  private static final int REQUEST_PICTUREE = 11;
  private static final int REQUEST_PICTUREF = 12;
  private int REQUEST_ATTENT_EXPERT = 9;
  private int REQUEST_TREE = 10;

  private TextView tvSeviceType;// 圈子类别
  private TextView tvQuesttionType;// 帖子类别
  private EditText mTopicName;// 话题的名字
  private EditText mTopicContent;// 话题的内容
  private TextView tvAttentExpert;// @专家
  private EditText etName;// 姓名
  private EditText etPhone;// 手机号
  private TextView mTvFileForum;// 附件
  private ImageView mIvPictureAForum;
  private ImageView mIvPictureBForum;
  private ImageView mIvPictureCForum;
  private ImageView mIvPictureDForum;
  private ImageView mIvPictureEForum;
  private ImageView mIvPictureFForum;
  private CheckBox mIsAnonymityCb;// 是否匿名
  //人员可见范围
  private CheckBox mCbAll;// 公开全部
  private LinearLayout llVisibility;// 可见范围
  private CheckBox mCbFriend;// 好友
  private TextView mTvFriend;
  private CheckBox mCbCircle;// 圈子
  private TextView mTvCircle;
  private CheckBox mCbExpert;// 专家
  private TextView mTvExpert;

  private String topicKindCode;
  private String topicKindName;
  private String mFilePath;// 附件路径
  private String mTopicFileId;
  private String mFriend = "";
  private String mCircle = "";
  private String mExpert = "";
  private Expert mExpertContent;

  private String mPicturePathA;
  private String mPicturePathB;
  private String mPicturePathC;
  private String mPicturePathD;
  private String mPicturePathE;
  private String mPicturePathF;
  private String remindJobNo;
  private String collectTypeName;
  private String collectTypeCode;
  private String topicPicAAdds;
  private String topicPicBAdds;
  private String topicPicDAdds;
  private String topicPicCAdds;
  private String topicPicEAdds;
  private String topicPicFAdds;
  private double mLatitude;
  private double mLonitude;

  //高德定位
  public AMapLocationClient mLocationClient;
  public AMapLocationListener mLocationListener = new MyLocationListener();
  //声明mLocationOption对象
  public AMapLocationClientOption mLocationOption = null;
  private String mFrom = "";
  private LinearLayout llSeviceType;
  private int count = 0;
  private LinkedHashMap<String, String> files;

  /**
   * 传递数据
   */
  public static Fragment newInstance(CompanyForumType type, Expert expert, String from) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_FORUM_TYPE, type);
    bundle.putSerializable(EXTRA_FROM, expert);
    bundle.putString(EXTRA_TYPE, from);
    AgriculturalTopicPublishFragment fragment = new AgriculturalTopicPublishFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.publishTopic);
    CompanyForumType mTopicType =
        (CompanyForumType) getArguments().getSerializable(EXTRA_FORUM_TYPE);
    mExpertContent = (Expert) getArguments().getSerializable(EXTRA_FROM);
    mFrom = getArguments().getString(EXTRA_TYPE);
    LogUtil.i("帖子发布mFrom==" + mFrom);
    if (mTopicType != null) {
      topicKindCode = mTopicType.getCustomAttrs();
      topicKindName = mTopicType.getName();
    }
    // 启动定位
    getLocation();
  }

  private void getLocation() {
    // 启动定位
    mLocationClient = new AMapLocationClient(MyApplication.getAppContext());
    mLocationClient.setLocationListener(mLocationListener);
    //初始化定位参数
    mLocationOption = new AMapLocationClientOption();
    //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
    //设置是否返回地址信息（默认返回地址信息）
    mLocationOption.setNeedAddress(true);
    //设置是否强制刷新WIFI，默认为强制刷新
    mLocationOption.setWifiActiveScan(true);
    //设置是否允许模拟位置,默认为false，不允许模拟位置
    mLocationOption.setMockEnable(false);
    mLocationOption.setLocationCacheEnable(false);
    //设置是否只定位一次,默认为false
    mLocationOption.setOnceLocation(false);
    //设置定位间隔,单位毫秒,默认为2000ms,设置之后startLocation经过间隔时间才返回结果.
    mLocationOption.setInterval(1000 * 30);
    //给定位客户端对象设置定位参数
    mLocationClient.setLocationOption(mLocationOption);
    mLocationClient.stopLocation();
    //启动定位
    mLocationClient.startLocation();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_agricultural_publish_topic, container, false);
    llSeviceType = (LinearLayout) view.findViewById(R.id.ll_seviceType);
    tvSeviceType = (TextView) view.findViewById(R.id.tv_seviceType);
    tvQuesttionType = (TextView) view.findViewById(R.id.tv_questtionType);
    mTopicName = (EditText) view.findViewById(R.id.et_topicName);
    mTopicContent = (EditText) view.findViewById(R.id.et_topicContent);
    tvAttentExpert = (TextView) view.findViewById(R.id.tv_attentExpert);
    etName = (EditText) view.findViewById(R.id.et_name);
    etPhone = (EditText) view.findViewById(R.id.et_phone);
    mIvPictureAForum = (ImageView) view.findViewById(R.id.iv_pictureA_forumPublish);
    mIvPictureBForum = (ImageView) view.findViewById(R.id.iv_pictureB_forumPublish);
    mIvPictureCForum = (ImageView) view.findViewById(R.id.iv_pictureC_forumPublish);
    mIvPictureDForum = (ImageView) view.findViewById(R.id.iv_pictureD_forumPublish);
    mIvPictureEForum = (ImageView) view.findViewById(R.id.iv_pictureE_forumPublish);
    mIvPictureFForum = (ImageView) view.findViewById(R.id.iv_pictureF_forumPublish);
    mTvFileForum = (TextView) view.findViewById(R.id.tv_file_forum);
    mIsAnonymityCb = (CheckBox) view.findViewById(R.id.cb_is_annoymity);
    //可见范围
    LinearLayout llPersonLook = (LinearLayout) view.findViewById(R.id.ll_person_look);
    llVisibility = (LinearLayout) view.findViewById(R.id.ll_visibility);
    mCbAll = (CheckBox) view.findViewById(R.id.cb_all);
    mCbFriend = (CheckBox) view.findViewById(R.id.cb_myFriend);
    mCbCircle = (CheckBox) view.findViewById(R.id.cb_myCircle);
    mCbExpert = (CheckBox) view.findViewById(R.id.cb_myExpert);
    mTvFriend = (TextView) view.findViewById(R.id.tv_myFriend);
    mTvCircle = (TextView) view.findViewById(R.id.tv_myCircle);
    mTvExpert = (TextView) view.findViewById(R.id.tv_myExpert);
    mCbAll.setChecked(true);
    mCbFriend.setEnabled(false);
    mCbCircle.setEnabled(false);
    mCbExpert.setEnabled(false);
    //来自咨询
    if (mExpertContent != null) {
      llPersonLook.setVisibility(View.GONE);
      tvAttentExpert.setText(mExpertContent.getMembername());
    }
    //来自我的话题,需选择具体圈子
    if (mFrom != null && SELF.equalsIgnoreCase(mFrom)) {
      llSeviceType.setVisibility(View.VISIBLE);
    } else {
      llSeviceType.setVisibility(View.GONE);
    }
    LinearLayout mIvAddFileForum = (LinearLayout) view.findViewById(R.id.iv_addFile_forum);
    tvSeviceType.setOnClickListener(this);
    tvQuesttionType.setOnClickListener(this);
    tvAttentExpert.setOnClickListener(this);
    mIvAddFileForum.setOnClickListener(this);
    mIvPictureAForum.setOnClickListener(this);
    mIvPictureBForum.setOnClickListener(this);
    mIvPictureCForum.setOnClickListener(this);
    mIvPictureDForum.setOnClickListener(this);
    mIvPictureEForum.setOnClickListener(this);
    mIvPictureFForum.setOnClickListener(this);
    mTvFriend.setOnClickListener(this);
    mTvCircle.setOnClickListener(this);
    mTvExpert.setOnClickListener(this);
    mCbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
        if (isCheck) {
          mCbFriend.setEnabled(false);
          mCbCircle.setEnabled(false);
          mCbExpert.setEnabled(false);
          llVisibility.setVisibility(View.GONE);
        }
        if (!isCheck) {
          mCbFriend.setEnabled(true);
          mCbCircle.setEnabled(true);
          mCbExpert.setEnabled(true);
          llVisibility.setVisibility(View.VISIBLE);
        }
      }
    });
    CurrentUser mUser = CurrentUser.newInstance(getActivity());
    if (!TextUtils.isEmpty(mUser.getRealName())) {
      etName.setText(mUser.getRealName());
      etName.setEnabled(false);
    }
    if (!TextUtils.isEmpty(mUser.getMobile())) {
      etPhone.setText(mUser.getMobile());
    }
    return view;
  }

  /**
   * 添加发布按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_forum_reply, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回按钮
      case android.R.id.home:
        getActivity().finish();
        return true;

      // 响应发布按钮
      case R.id.menu_item_reply:
        contentExamineSave();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  protected void contentExamineSave() {
    boolean isEmpty = TextUtils.isEmpty(tvQuesttionType.getText().toString())
        || TextUtils.isEmpty(mTopicName.getText().toString())
        || TextUtils.isEmpty(mTopicContent.getText().toString())
        || TextUtils.isEmpty(etName.getText().toString())
        || ("01".equalsIgnoreCase(collectTypeCode) && TextUtils.isEmpty(
        etPhone.getText().toString()));
    if (isEmpty) {
      ToastUtil.show(R.string.notComplete);
      return;
    }

    volleyPostSave();// 发布内容
  }

  private void volleyPostSave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGEFORUM_POST_UPDATE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    String topicTitle = mTopicName.getText().toString();
    String topicContentStr = mTopicContent.getText().toString();
    //新建的时候通过key-value方式传递,与修改不同.
    mTopicFileId = UUID.randomUUID().toString();
    params.put("id", mTopicFileId);
    params.put("dataStatus", "new");
    params.put("topicKindCode", topicKindCode);
    params.put("topicKindName", topicKindName);
    params.put("topicTitle", topicTitle);
    params.put("topicContents", topicContentStr);

    params.put("collectType", collectTypeName);//帖子类型
    params.put("collectTypeCode", collectTypeCode);
    params.put("remindJobNo", remindJobNo);//@专家
    params.put("topicPicAAdds", topicPicAAdds);//图片a经纬度
    params.put("topicPicBAdds", topicPicBAdds);//图片b
    params.put("topicPicCAdds", topicPicCAdds);//图片c
    params.put("topicPicDAdds", topicPicDAdds);//图片d
    params.put("topicPicEAdds", topicPicEAdds);//图片E
    params.put("topicPicFAdds", topicPicFAdds);//图片F
    LocationUtil.newInstance(getActivity());
    params.put("longitude", mCurrentUser.getLongitude());//当前定位经度
    params.put("latitude", mCurrentUser.getLatitude());//当前定位纬度
    params.put("location", mCurrentUser.getAddress());//当前定位地址
    params.put("fullname", etName.getText().toString());
    params.put("mobile", etPhone.getText().toString());

    if (mIsAnonymityCb.isChecked()) {
      params.put("ifDisPlay", "T");
    } else {
      params.put("ifDisPlay", "F");
    }
    //来自咨询,可见范围为自自选的专家
    if (mExpertContent != null) {
      params.put("limitPersonal", mExpertContent.getJobno() + "T");
    } else {
      //如果选中了查看人员,
      if (!mCbAll.isChecked()) {
        params.put("limitPersonal", mFriend + "," + mExpert + "," + mCircle);
      } else {
        //如果没有勾选,就是全部,传""
        params.put("limitPersonal", "");
      }
    }
    MyUtils.showDialogLoading(getActivity(), "正在发帖...");
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            MyUtils.dismissDialog();
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = success.getResult();
          if (successType.equals("0")) {
            MyUtils.dismissDialog();
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals("1")) {
            files = new LinkedHashMap<>();
            if (!MyStringUtil.isEmpty(mFilePath)) {
              // 选择了附件
              files.put("topicFile", mFilePath);
            }
            if (!MyStringUtil.isEmpty(mPicturePathA)) {
              files.put("topicPicA", mPicturePathA);
            }
            if (!MyStringUtil.isEmpty(mPicturePathB)) {
              files.put("topicPicB", mPicturePathB);
            }
            if (!MyStringUtil.isEmpty(mPicturePathC)) {
              files.put("topicPicC", mPicturePathC);
            }
            if (!MyStringUtil.isEmpty(mPicturePathD)) {
              files.put("topicPicD", mPicturePathD);
            }
            if (!MyStringUtil.isEmpty(mPicturePathE)) {
              files.put("topicPicE", mPicturePathE);
            }
            if (!MyStringUtil.isEmpty(mPicturePathF)) {
              files.put("topicPicF", mPicturePathF);
            }
            if (files.size() == 0) {
              MyUtils.dismissDialog();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else {
              for (String fieldName : files.keySet()) {
                String path = files.get(fieldName);
                if (!TextUtils.isEmpty(path)) {
                  if ("topicFile".equalsIgnoreCase(fieldName)) {
                    volleyPostSaveFile(fieldName, path, false);
                  } else {
                    volleyPostSaveFile(fieldName, path, true);
                  }
                }
              }
            }
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  /**
   * 附件上传
   */
  private void volleyPostSaveFile(final String fieldName, String path, boolean isthumbnail) {
    String url = ApiConst.URL_TOPIC_FILEUPLOAD;
    HashMap<String, String> params = new HashMap<>();
    //韦加表名
    params.put("curtabName", "imsifwj.wj_erp_o_enterpriseforum_main");
    params.put("curid", mTopicFileId);
    params.put("fieldName", fieldName);
    if (isthumbnail) {
      //是否需要缩略图
      params.put("imageForVigaApp", "true");
    }
    LogUtil.i(fieldName + "===" + params.toString());
    MyUtils.showDialogLoading(getActivity(), "正在发帖...");
    new FileNetWorkUtil(getActivity()).upLoadFile(path, url, params,
        new AsyncHttpResponseHandler() {

          @Override public void onSuccess(int arg0, Header[] arg1, byte[] response) {

            try {
              count++;
              SuccessMessage message =
                  new Gson().fromJson(new String(response), SuccessMessage.class);
              if (message != null && SuccessMessage.SUCCESS.equals(message.getResult())) {
                ToastUtil.show(R.string.fileSuccess);
              } else {
                ToastUtil.show(R.string.fileFail);
              }
              if (count == files.size()) {
                MyUtils.dismissDialog();
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
              }
            } catch (Exception e) {
              LogUtil.e("fileUploadError", e);
              ToastUtil.show(R.string.fileFail);
            }
          }

          @Override
          public void onFailure(int arg0, Header[] arg1, byte[] errorResponse, Throwable arg3)
              throws NullPointerException {
            ToastUtil.show(R.string.fileFail);
          }
        });
  }

  /**
   * 处理点击事件
   */
  @Override public void onClick(View v) {
    switch (v.getId()) {

      // 圈子类别树
      case R.id.tv_seviceType:
        volleyGetCircle();
        break;

      // 帖子类别
      case R.id.tv_questtionType:
        showDialog(new ToipKindDialogFrament(), REQUEST_TOPIC_KIND);
        break;

      // @专家列表
      case R.id.tv_attentExpert:
        if (topicKindCode != null && !TextUtils.isEmpty(topicKindCode)) {
          Intent attentExpert = new Intent(getActivity(), ExpertChooseListActvity.class);
          attentExpert.putExtra(ExpertChooseListFragment.EXTAR_VALUE, topicKindCode);
          startActivityForResult(attentExpert, REQUEST_ATTENT_EXPERT);
        } else {
          if (llSeviceType.getVisibility() == View.VISIBLE) {
            ToastUtil.show("请先选择圈子类别!");
          }
        }
        break;

      // 添加附件
      case R.id.iv_addFile_forum:
        chooseFileDialog();
        break;

      // 图片A
      case R.id.iv_pictureA_forumPublish:
        if (isPictureIfExist(mIvPictureAForum)) {
          choosePictureDialogA(REQUEST_PICTUREA);
        }
        break;

      // 图片B
      case R.id.iv_pictureB_forumPublish:
        if (isPictureIfExist(mIvPictureBForum)) {
          choosePictureDialogA(REQUEST_PICTUREB);
        }
        break;

      // 图片C
      case R.id.iv_pictureC_forumPublish:
        if (isPictureIfExist(mIvPictureCForum)) {
          choosePictureDialogA(REQUEST_PICTUREC);
        }
        break;

      // 图片D
      case R.id.iv_pictureD_forumPublish:
        if (isPictureIfExist(mIvPictureDForum)) {
          choosePictureDialogA(REQUEST_PICTURED);
        }
        break;

      // 图片E
      case R.id.iv_pictureE_forumPublish:
        if (isPictureIfExist(mIvPictureEForum)) {
          choosePictureDialogA(REQUEST_PICTUREE);
        }
        break;

      // 图片F
      case R.id.iv_pictureF_forumPublish:
        if (isPictureIfExist(mIvPictureFForum)) {
          choosePictureDialogA(REQUEST_PICTUREF);
        }
        break;

      // 我的好友多选列表
      case R.id.tv_myFriend:
        if (isNotAll(mCbFriend)) {
          Intent friend = new Intent(getActivity(), MyFriendMultiListActvity.class);
          startActivityForResult(friend, REQUEST_FRIEND);
        }
        break;

      // 我的圈子多选列表
      case R.id.tv_myCircle:
        if (isNotAll(mCbCircle)) {
          Intent circle = new Intent(getActivity(), MyCircleMultiListActvity.class);
          startActivityForResult(circle, REQUEST_CIRCLE);
        }
        break;

      // 我关注的专家多选列表
      case R.id.tv_myExpert:
        if (isNotAll(mCbExpert)) {

          Intent expert = new Intent(getActivity(), MyExpertMultiListActvity.class);
          startActivityForResult(expert, REQUEST_EXPERT);
        }
        break;

      default:
        break;
    }
  }

  private boolean isNotAll(CheckBox cb) {
    if (mCbAll.isChecked()) {
      ToastUtil.show("不可选,已经选择全部可见");
      return false;
    }
    if (!mCbAll.isChecked()) {
      if (!cb.isChecked()) {
        ToastUtil.show("请先勾选");
        return false;
      }
    }
    return true;
  }

  /**
   * 判断图片是否为空
   *
   * @param iv ImageView空间
   * @return 返回boolean值，如果不为空提示，返回false，如果为空返回true
   */
  public boolean isPictureIfExist(final ImageView iv) {
    if (MyUtils.isEmptyText(tvQuesttionType)) {
      ToastUtil.show("请先选择帖子类型");
      return false;
    }
    if (iv.getDrawable() != null) {
      AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
      dialog.setTitle(R.string.restart_title);
      dialog.setMessage(R.string.ifChangePicture);
      dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

        @Override public void onClick(DialogInterface dialog, int which) {
          // 设置为空
          iv.setImageDrawable(null);
          iv.setBackgroundResource(R.drawable.add_photo);
        }
      });
      dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

        @Override public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      });

      dialog.create().show();
      return false;
    }
    return true;
  }

  /**
   * 选择附件
   */
  private void chooseFileDialog() {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog = new KnowledgeForumTopicFileDialogFragment();
    dialog.setTargetFragment(AgriculturalTopicPublishFragment.this, CHOOSE_FILE);
    dialog.show(fm, "");
  }

  /**
   * 添加图片A选择拍照还是图库
   */
  public void choosePictureDialogA(int requestCode) {
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog =
        ExtraUpLoadDialogFragment.newInstance("", ExtraUpLoadDialogFragment.TYPE_PHOTO);
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  /** 测试项目类别 */
  private void volleyGetCircle() {
    String subCode =
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, "");
    SimpleTreeListParams params = new SimpleTreeListParams();
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    if ("01".equalsIgnoreCase(subCode)) {
      params.setTitle("农作物圈");
    }
    if ("02".equalsIgnoreCase(subCode)) {
      params.setTitle("农机服务圈");
    }
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_FORUM_CIRCLE_LIST);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);//只能选择最底层节点
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dictFlg", "topicKindDataWJ")
            .put("type", "mobile")
            .put("subCode", subCode));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_TREE);
  }

  /**
   * 处理返回按钮和返回的图片、附件
   */
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_TREE && data != null) {
      //圈子类别树
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      topicKindName = item.getName();
      topicKindCode = item.getCustomAttrs();
      tvSeviceType.setText(topicKindName);
    }
    if (requestCode == CHOOSE_FILE && data != null) {
      // 添加附件
      mFilePath = data.getStringExtra(KnowledgeForumTopicFileDialogFragment.EXTRA_RESULT);
      LogUtil.i("附件mPath=====" + mFilePath);
      if (mFilePath != null) {
        String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath);
        mTvFileForum.setText(mChoseFileName);
      }
    }
    if (requestCode == REQUEST_FRIEND && data != null) {
      // 我的好友复选列表: jobno
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(MyFriendMultiListFragment.EXTRA_VALUE);
      mFriend = content.getId();
      mTvFriend.setText(content.getName());
    }
    if (requestCode == REQUEST_CIRCLE && data != null) {
      // 我的圈子复选列表: id
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(MyCircleMultiListFragment.EXTRA_VALUE);
      mCircle = content.getId();
      mTvCircle.setText(content.getName());
    }
    if (requestCode == REQUEST_EXPERT && data != null) {
      // 我的专家复选列表
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(MyExpertMultiListFragment.EXTRA_VALUE);
      mExpert = content.getId();
      mTvExpert.setText(content.getName());
    }

    String pictureResult;
    if (requestCode == REQUEST_PICTUREA
        || requestCode == REQUEST_PICTUREB
        || requestCode == REQUEST_PICTUREC
        || requestCode == REQUEST_PICTURED
        || requestCode == REQUEST_PICTUREE
        || requestCode == REQUEST_PICTUREF) {

      // 获取返回的图片，并添加

      int typePosition = data.getIntExtra(ExtraUpLoadDialogFragment.EXTRA_POSITION, 0);
      String absolutePath = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_ABSOLUTEPATH);
      pictureResult = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      LogUtil.i("图片absolutePath=====" + absolutePath);
      LogUtil.i("图片pictureResult=====" + pictureResult);
      //帖子类型为病情咨询时才获取经纬度
      // 相册: 图片获取经纬度, 拍照: 高德定位
      String picAdds = "";
      if (ExtraUpLoadDialogFragment.ALBUM == typePosition && "01".equalsIgnoreCase(
          collectTypeCode)) {
        picAdds = getImageExifInterfaceData(absolutePath);//获取经纬度
      }

      if (ExtraUpLoadDialogFragment.CAMERA == typePosition && "01".equalsIgnoreCase(
          collectTypeCode)) {
        //启动定位
        if (!TextUtils.isEmpty(String.valueOf(mLatitude)) && !TextUtils.isEmpty(
            String.valueOf(mLonitude))) {
          picAdds = "n:" + mLatitude + ",w:" + mLonitude;
        } else {
          ToastUtil.show("请先打开定位");
        }
      }

      if ("01".equalsIgnoreCase(collectTypeCode) && TextUtils.isEmpty(picAdds)) {
        return;
      } else {
        Bitmap bitmap = BitmapFactory.decodeFile(pictureResult);
        switch (requestCode) {
          case REQUEST_PICTUREA:
            topicPicAAdds = picAdds;
            mPicturePathA = absolutePath;
            if (mPicturePathA != null) {
              mIvPictureAForum.setBackgroundColor(Color.WHITE);
              mIvPictureAForum.setImageBitmap(bitmap);
            }
            mIvPictureBForum.setVisibility(View.VISIBLE);
            break;
          case REQUEST_PICTUREB:
            topicPicBAdds = picAdds;
            mPicturePathB = absolutePath;
            if (mPicturePathB != null) {
              mIvPictureBForum.setBackgroundColor(Color.WHITE);
              mIvPictureBForum.setImageBitmap(bitmap);
            }
            mIvPictureCForum.setVisibility(View.VISIBLE);
            break;
          case REQUEST_PICTUREC:
            topicPicCAdds = picAdds;
            mPicturePathC = absolutePath;
            if (mPicturePathC != null) {
              mIvPictureCForum.setBackgroundColor(Color.WHITE);
              mIvPictureCForum.setImageBitmap(bitmap);
            }
            mIvPictureDForum.setVisibility(View.VISIBLE);
            break;
          case REQUEST_PICTURED:
            topicPicDAdds = picAdds;
            mPicturePathD = absolutePath;
            if (mPicturePathD != null) {
              mIvPictureDForum.setBackgroundColor(Color.WHITE);
              mIvPictureDForum.setImageBitmap(bitmap);
            }
            mIvPictureEForum.setVisibility(View.VISIBLE);
            break;
          case REQUEST_PICTUREE:
            topicPicEAdds = picAdds;
            mPicturePathE = absolutePath;
            if (mPicturePathE != null) {
              mIvPictureEForum.setBackgroundColor(Color.WHITE);
              mIvPictureEForum.setImageBitmap(bitmap);
            }
            mIvPictureFForum.setVisibility(View.VISIBLE);
            break;
          case REQUEST_PICTUREF:
            topicPicFAdds = picAdds;
            mPicturePathF = absolutePath;
            if (mPicturePathF != null) {
              mIvPictureFForum.setBackgroundColor(Color.WHITE);
              mIvPictureFForum.setImageBitmap(bitmap);
            }
            break;
          default:
            break;
        }
      }
    }
    if (requestCode == REQUEST_TOPIC_KIND && data != null) {
      // 帖子类型

      CustomerDialog toipcKind =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      collectTypeName = toipcKind.getName();
      collectTypeCode = toipcKind.getId();
      tvQuesttionType.setText(collectTypeName);
      if ("01".equalsIgnoreCase(collectTypeCode)) {
        mTopicContent.setHint(R.string.topicHint);
        mTopicContent.setHintTextColor(Color.RED);
        etPhone.setHint(R.string.inputMust);//病情咨询时电话为必填
      } else {
        mTopicContent.setHint(R.string.topicDetail);
        mTopicContent.setHintTextColor(Color.GRAY);
        etPhone.setHint("");
      }
    }
    if (requestCode == REQUEST_ATTENT_EXPERT && data != null) {
      // @专家列表
      SeniorExpert content =
          (SeniorExpert) data.getSerializableExtra(ExpertChooseListFragment.EXTAR_VALUE);
      remindJobNo = content.getExportJobno();
      tvAttentExpert.setText(content.getExportName());
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 获取照片其他附属属性
   */
  public String getImageExifInterfaceData(String imagePath) {
    ExifInterface exifInterface;
    try {
      exifInterface = new ExifInterface(imagePath);
      //String datetime = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);// 拍摄时间
      String deviceName = exifInterface.getAttribute(ExifInterface.TAG_MAKE);// 设备品牌
      //String deviceModel = exifInterface.getAttribute(ExifInterface.TAG_MODEL); // 设备型号
      String latValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
      String lngValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
      String latRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
      String lngRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
      if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
        float lat = convertRationalLatLonToFloat(latValue, latRef);//纬度
        float lon = convertRationalLatLonToFloat(lngValue, lngRef);//经度
        double[] item = GPSToGCJUtil.transform(lon, lat);
        double mLon = item[0];
        double mLat = item[1];

        /*n: 纬度 , w: 经度*/
        //String latlng = "n:" + lat + ",w:" + lon;
        String latlng = "n:" + mLat + ",w:" + mLon;
        LogUtil.i("设备经纬度==" + deviceName + ",经度==" + lon + ",纬度==" + lat);
        LogUtil.i("高德经纬度==" + deviceName + ",经度==" + mLon + ",纬度==" + mLat);
        return latlng;
      } else {
        ToastUtil.show("该图片没有位置不能上传");
        return "";
      }
    } catch (IOException e) {
      e.printStackTrace();
      return "";
    }
  }

  /**
   * 目前想存储Double类型坐标，但是通过getAttribute(String tag)取出来的内容形如：
   * 112/1,39/1 , 288172/3278,其实就是“度分秒”拆分后，分母除以1的结果
   */
  private static float convertRationalLatLonToFloat(String rationalString, String ref) {

    String[] parts = rationalString.split(",");

    String[] pair;
    pair = parts[0].split("/");
    double degrees = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());

    pair = parts[1].split("/");
    double minutes = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());

    pair = parts[2].split("/");
    double seconds = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());

    double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
    if ((ref.equals("S") || ref.equals("W"))) {
      return (float) -result;
    }
    return (float) result;
  }

  public class MyLocationListener implements AMapLocationListener {

    @Override public void onLocationChanged(AMapLocation location) {
      if (location != null) {
        if (location.getErrorCode() == 0) {
          mLatitude = location.getLatitude();
          mLonitude = location.getLongitude();
          LogUtil.i("高德定位==" + mLatitude + " , " + mLonitude);
        }
      }
    }
  }
}